import request from "./request";
import base64 from "base64-js";
/**
 * 解析 token
 *
 * @param {string} token JWT 字符串
 * @returns {{payload: any, header: any}} 解析后的对象
 */
export function parseToken(token) {
  let decoder = new TextDecoder();
  let tokenHeader = token
    .split(".")[0]
    .replace(/-/gi, "+")
    .replace(/_/gi, "/");
  let tokenPayload = token
    .split(".")[1]
    .replace(/-/gi, "+")
    .replace(/_/gi, "/");
  while (tokenPayload.length % 4 !== 0) tokenPayload += "=";
  while (tokenHeader.length % 4 !== 0) tokenHeader += "=";
  let jsonStr = decoder.decode(base64.toByteArray(tokenPayload));
  let payload = JSON.parse(jsonStr);
  jsonStr = decoder.decode(base64.toByteArray(tokenHeader));
  let header = JSON.parse(jsonStr);
  return {
    header: header,
    payload: payload
  };
}

/**
 * 刷新令牌
 * @return {Promise<string>} 返回的 Refresh Token
 */
export async function getRefreshToken() {
  return await request
    .get("/oauth/refreshToken")
    .then(result => {
      let data = result.data;
      let refreshToken = data["refreshToken"];
      return refreshToken;
    })
    .catch(() => '');
}
